<template>
	<view class="wrapper">
		<!-- 总资产 -->
		<view class="total-assets bg-red-500 text-white p-4 rounded-lg mb-4">
			<view class="flex justify-between items-center">
				<view class="text-xl font-bold">总资产（元）</view>
				<view class="text-sm" @click="goToRechargeRecord">充值记录</view>
			</view>
			<view class="text-3xl font-bold mt-2">{{ totalAssets }}</view>
		</view>

		<view class="total-assets bg-white">
			<!-- 充值金额输入 -->
			<view class="recharge-amount p-4 rounded-lg mb-4 relative">
				<view class="text-gray-700 mb-2">充值金额</view>
				<input v-model="rechargeAmount" type="number" placeholder="请输入充值金额"
					class="border border-gray-300 p-2 rounded-lg w-full">
				<view class="underline bg-gray-200 absolute bottom-0 left-0 right-0 h-0.5"></view>
			</view>

			<!-- 快捷充值 -->
			<view class="quick-recharge p-4 rounded-lg mb-4">
				<view class="text-gray-700 mb-2">快捷充值</view>
				<view class="flex justify-start">
					<view v-for="(item, index) in quickRechargeOptions" :key="index" :class="[
                            'quick-option',
                            {
                                'bg-red-500 text-white': selectedQuickOption === index,
                                'bg-gray-100': selectedQuickOption!== index
                            }
                        ]" @click="selectQuickOption(index)">
						<view class="text-xl font-bold mb-1">{{ item.amount }}元</view>
						<view class="text-xs">充值价{{ item.discountPrice }}元</view>
					</view>
				</view>
			</view>

			<!-- 立即充值按钮 -->
			<view class="recharge-button p-4 rounded-lg mb-4">
				<button @click="handleRecharge" class="bg-red-500 text-white p-2 rounded-lg w-full">立即充值</button>
			</view>
		</view>

		<!-- 充值说明 -->
		<view class="recharge-note bg-white p-4 rounded-lg">
			<view class="text-gray-700 mb-2">充值说明</view>
			<view class="text-sm text-gray-600">{{ rechargeNote }}</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		owneRegister
	} from '@/api/indextwo.js';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		ziChanAPI
	} from '@/package/api/zichan.js';

	// 总资产，添加测试数据
	const totalAssets = ref(0);
	// 充值金额输入框的值，初始值设为50
	const rechargeAmount = ref('50');
	// 快捷充值选项，添加测试数据
	const quickRechargeOptions = ref([{
			amount: 50,
			discountPrice: 45
		},
		{
			amount: 150,
			discountPrice: 135
		},
		{
			amount: 250,
			discountPrice: 225
		}
	]);
	// 当前选中的快捷充值选项索引
	const selectedQuickOption = ref(0);
	// 充值说明，添加测试数据
	const rechargeNote = ref('请仔细确认充值金额');

	// 选择快捷充值选项
	const selectQuickOption = (index) => {
		selectedQuickOption.value = index;
		rechargeAmount.value = quickRechargeOptions.value[index].amount;
	};

	// 立即充值逻辑（实际应调用支付接口等）
	const handleRecharge = () => {
		if (selectedQuickOption.value !== null) {
			console.log('选择快捷充值，金额:', quickRechargeOptions.value[selectedQuickOption.value].amount);
			handleWechatPay();
		} else if (rechargeAmount.value) {
			console.log('输入金额充值，金额:', rechargeAmount.value);
		} else {
			uni.showToast({
				title: '请选择充值金额或输入金额',
				icon: 'none'
			});
		}
	};

	// 跳转到充值记录页面（实际需配置相应页面路由）
	const goToRechargeRecord = () => {
		uni.navigateTo({
			url: '/pages/rechargeRecord'
		});
	};

	onShow(() => {
		// 从本地存储中获取用户资产金额
		totalAssets.value = uni.getStorageSync('totalAssets');
	});

	const handleWechatPay = async () => {
		// 封装请求参数
		const requestData = {
			xianMonery: totalAssets.value.toString(),
			bianMonery: rechargeAmount.value.toString(),
			zongMonery: (parseFloat(totalAssets.value) + parseFloat(rechargeAmount.value)).toString(),
			type: 1
		};

		const jsonData = JSON.stringify(requestData);
		console.log("1---------------------------------------");
		// 向资产记录表中添加一条数据 后续如果取消支付则根据id进行删除
		const res = await ziChanAPI.addZiChan(jsonData);
		console.log("---------------------------------------");
		console.log(res);

		// 微信支付
		// 查询出需要支付的订单号
		// 新增订单号，并返回
		try {
			// 查询订单号
			let payData = {
				orderNo: res.data
			};
			let payres = await owneRegister.submitCarInfoPay(payData);
			console.log(payres, 123);
			if (payres.code === 200) {
				wx.requestPayment({
					timeStamp: payres.data.jsConfig.timeStamp,
					nonceStr: payres.data.jsConfig.nonceStr,
					package: payres.data.jsConfig.packageVal,
					paySign: payres.data.jsConfig.paySign,
					signType: payres.data.jsConfig.signType, // 该参数为固定值
					success: async (res) => {
						// 将 payData 转换为 JSON 格式
						let payData = {
							monery: rechargeAmount.value
						};
						let payDataJSON = JSON.stringify(payData);
						// 发起更新用户总资产请求
						const updateRes = await ziChanAPI.updateUser(payDataJSON);
						// 判断更新请求的返回结果
						if (updateRes && updateRes.code === 200) {
							// 更新成功，更新本地存储的总资产
							totalAssets.value = parseFloat(totalAssets.value) + parseFloat(
								rechargeAmount.value);
							uni.setStorageSync('totalAssets', totalAssets.value);
							uni.showToast({
								title: '支付成功且总资产更新成功',
								icon: 'none'
							});
						} else {
							uni.showToast({
								title: '支付成功，但总资产更新失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						// 支付失败回调
						console.error('唤起支付组件失败：', err);
						//根据资产记录id 进行删除  
						ziChanAPI.deleteZiChanById(res.data);
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						});
					}
				});
			}
		} catch (error) {
			console.log(error);
		}
		// 调用支付，调用回调
	};
</script>

<style scoped>
	.wrapper {
		padding: 10px;
	}

	.total-assets {
		position: relative;
	}

	.recharge-amount,
	.quick-recharge,
	.recharge-button,
	.recharge-note {
		margin-bottom: 15px;
	}

	.quick-option {
		padding: 10px 15px;
		border-radius: 5px;
		margin-right: 10px;
		cursor: pointer;
		text-align: center;
		display: inline-block;
	}

	.underline {
		margin-top: 5px;
	}
</style>